﻿using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEngine;

namespace UnityEditor.XCodeEditor
{
    /// <summary>
    /// Unity3d 打包Xcode工程自动添加framework
    /// </summary>
    public class AfterBuildAddFrameworks : MonoBehaviour
    {
        public const string JPUSHAPPKEY = "KeyOfJpushAppKeyString";
        public const string SwitchClassName = "CYTLVTWO_LaunchViewController";

        //该属性是在build完成后，被调用的callback
        [PostProcessBuildAttribute(10)]
        public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuiltProject)
        {
            // BuildTarget需为iOS
            if (buildTarget != BuildTarget.iOS)
                return;

            // 初始化
            string projPath = PBXProject.GetPBXProjectPath(pathToBuiltProject);
            PBXProject pbxProject = new PBXProject();
            pbxProject.ReadFromString(File.ReadAllText(projPath));
            string targetGuid = "";
#if UNITY_2019 || UNITY_2020
            targetGuid = pbxProject.GetUnityFrameworkTargetGuid();
#else
            targetGuid = pbxProject.TargetGuidByName("Unity-iPhone");
#endif
            // 添加framework
            pbxProject.AddFrameworkToProject(targetGuid, "CoreFoundation.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "CFNetwork.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "SystemConfiguration.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "CoreTelephony.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "CoreGraphics.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "Foundation.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "UIKit.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "libz.tbd", false);
            pbxProject.AddFrameworkToProject(targetGuid, "AdSupport.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "libresolv.tbd", false);
            pbxProject.AddFrameworkToProject(targetGuid, "UserNotifications.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "Security.framework", false);
            pbxProject.AddFrameworkToProject(targetGuid, "WebKit.framework", false);

            Debug.Log("添加库引用成功");

            // 应用修改

            File.WriteAllText(projPath, pbxProject.WriteToString());


            //修改代码
            string fullPathProject = Path.GetFullPath(pathToBuiltProject);
            AutoChangeSDKCode UnityAppController = new AutoChangeSDKCode(fullPathProject + "/Classes/UnityAppController.mm");
            UnityAppController.WriteBelow("#include \"PluginBase/AppDelegateListener.h\"", "#include \"" + SwitchClassName + ".h\"\n#import \"JPUSHService.h\"\n#import \"JPushEventCache.h\"\n#import <UserNotifications/UserNotifications.h>");
            UnityAppController.WriteBelow("// send notfications", "_startUnityScheduled=true;");
            UnityAppController.OverwriteBetween("UnityInitApplicationNoGraphics(UnityDataBundleDir());", "[KeyboardDelegate Initialize];", "_window  = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];\n_window.backgroundColor = [UIColor blackColor];\n["
        + SwitchClassName + @" getAppDataWithDelegate:self andBackBlock:^(NSInteger type) {
                if (type == 1) {
                    
                    _startUnityScheduled=false;
                    [self selectRenderingAPI];
                    [UnityRenderingView InitializeForAPI: self.renderingAPI];

                    _window         = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];
                    
                    _unityView      = [self createUnityView];

                    [DisplayManager Initialize];
                    _mainDisplay    = [DisplayManager Instance].mainDisplay;
                    [_mainDisplay createWithWindow: _window andView: _unityView];
                    
                    [self createUI];
                    [self preStartUnity];
                    
                    //
                    [self removeSnapshotViewController];

                    if (_unityAppReady)
                    {
                        if (UnityIsPaused() && _wasPausedExternal == false)
                        {
                            UnityWillResume();
                            UnityPause(0);
                        }
                        if (_wasPausedExternal)
                        {
                            if (UnityIsFullScreenPlaying())
                                TryResumeFullScreenVideo();
                        }
                        // need to do this with delay because FMOD restarts audio in AVAudioSessionInterruptionNotification handler
                        [self performSelector: @selector(updateUnityAudioOutput) withObject: nil afterDelay: 0.1];
                        UnitySetPlayerFocus(1);
                    }
                    else if (!_startUnityScheduled)
                    {
                       _startUnityScheduled = true;
                        [self performSelector: @selector(startUnity:) withObject: application afterDelay: 0];
                    }

                    _didResignActive = false;
                }
                else{
                                               
                }
    }];

");
            UnityAppController.WriteBelow("[KeyboardDelegate Initialize];", "[[JPushEventCache sharedInstance] handFinishLaunchOption:launchOptions];\n[JPUSHService setupWithOption: launchOptions appKey: @\"" + JPUSHAPPKEY + "\" channel: @\"\" apsForProduction: NO];\n[JPUSHService setBadge:0];\n[UIApplication sharedApplication].applicationIconBadgeNumber = 0; ");
            UnityAppController.WriteBelow("UnitySendDeviceToken(deviceToken);", "[JPUSHService registerDeviceToken:deviceToken];");
            UnityAppController.Replace("UnitySendRemoteNotification(userInfo);\n}", "UnitySendRemoteNotification(userInfo);\n[[JPushEventCache sharedInstance] sendEvent:userInfo withKey:@\"JPushPluginReceiveNotification\"];\n[JPUSHService handleRemoteNotification: userInfo]; \n}");
            UnityAppController.WriteBelow("handler(UIBackgroundFetchResultNoData);\n    }", "[[JPushEventCache sharedInstance] sendEvent:userInfo withKey:@\"JPushPluginReceiveNotification\"];");
            UnityAppController.WriteBelow("(NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window\n{", "return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;");
            Debug.Log("修改UnityController.m代码成功");
            AutoChangeSDKCode PreprocessorH = new AutoChangeSDKCode(fullPathProject + "/Classes/Preprocessor.h");
            PreprocessorH.Replace("#define UNITY_USES_REMOTE_NOTIFICATIONS 0", "#define UNITY_USES_REMOTE_NOTIFICATIONS 1");
            Debug.Log("修改Preprocessor.h代码成功");

        }


    }

}

